import { defineStore } from 'pinia'
import { useTtsaStore } from '../ttsa'
import { equ } from '../../../package-env'
import { useSub, useShare, useForm, useMenuTree } from '@/utils/comps'
import { useAppRouter } from '@/hooks'
import { useTrack } from '@/hooks'
import { uuid } from '@/utils/random'
import { WIDGETMAP } from '@/constants/ttsa'

const transName = ['translate', 'translate3d', 'translateX', 'translateY', 'translateZ', 'scale', 'scale3d', 'scaleX', 'scaleY', 'scaleZ', 'rotate', 'rotate3d', 'rotateX', 'rotateY', 'rotateZ', 'skew', 'skewX', 'skewY', 'perspective', 'matrix', 'matrix3d']

export const useUIStore = defineStore({
  id: 'UIStore',
  state: () => ({
    container: {},
    isSupportWebp: false,
  }),
  actions: {
    // 添加UI组件
    addUI(cfg) {
      const { axis_id = '-1' } = cfg
      const item = this.set(cfg)
      this.container[axis_id] = item
      if (item['animation-in']) this.animate(axis_id, 'in')
    },
    // 设置组件信息
    set(cfg) {
      const UIEVENTDATA = cfg || {}
      const {
        axis_id = '-1',
        type,
        event_click,
        'animation-in': aniIn
      } = UIEVENTDATA
      const mType = WIDGETMAP[type]
      let data = UIEVENTDATA[mType]
      if (mType === 'slides') {
        if (data?.id || data?.node_id) data = [data]
        data = data.map((n) => ({ ...n, id: uuid() }))
      }
      const res = {
        axis_id,
        ...cfg,
        data,
        handEvent: () => event_click && this.go({ ...event_click, axis_id }),
        style: this.setStyle(UIEVENTDATA),
      }
      if (aniIn) {
        res.style.transform = ''
        transName.forEach(n => {
          if (aniIn[n] !== undefined) res.style.transform += ` ${n}(${aniIn[n]})`
        })
      }
      return res
    },
    // 设置样式
    setStyle(cfg) {
      const { width, height, 'x-location': x, 'y-location': y, 'z-index': zIndex } = cfg
      // 视频原始宽高
      const ow = equ === 'pc' ? 1920 : 1080, oh = equ === 'pc' ? 834 : 1920
      // 屏幕宽高
      const vw = document.body.clientWidth, vh = document.body.clientHeight
      // 视频实际宽高
      const xw = ow / (oh / vh), xh = vh
      // 卡片宽高
      const w = xw * width, h = xh * height
      // 卡片位置
      const z = (xw - vw) / 2
      const l = xw * x - z, t = xh * y
      return {
        width: `${w}px`,
        height: `${h}px`,
        left: `${l}px`,
        top: `${t}px`,
        ...(zIndex && { 'z-index': zIndex })
      }
    },
    // 组件内点击操作
    go({ type, closed, content_node_id, content_id, axis_id, jump_type, turn_back, qa_content, link_url, table_id, update_enter = 'true' }) {
      if (closed !== 'false') this.delUI(axis_id)
      const { setTrack } = useTrack()
      setTrack({
        name: 'interactive',
        type: 'click'
      })
      const ttsa = useTtsaStore();
      switch (type) {
        case 'content':
          ttsa.next({ node_id: content_node_id, content_id, jump_type, update_enter: update_enter !== 'false' })
          break
        case 'qa':
          ttsa.turnBack = turn_back || ''
          ttsa.explainToQa(qa_content)
          break
        case 'link':
          useAppRouter(link_url)
          break
        case 'sub':
          useSub()
          break
        case 'share':
          useShare()
          break
        case 'menu':
          useMenuTree()
          break
        case 'form':
          useForm(table_id, true)
          break
        default:
          break
      }
    },
    // 删除Ui Event
    delUI(axis_id = '-1') {
      const fn = () => delete this.container[axis_id]
      const item = this.container[axis_id]
      if (item && item['animation-out']) this.animate(axis_id, 'out', () => fn())
      else fn()
    },
    // 清空store
    clear() {
      this.container = {}
    },
    // 动画效果
    animate(axis_id, type: string, callback?) {
      const item = this.container[axis_id], option = item[`animation-${type}`]
      const { duration = '1', 'timing-function': tf = 'linear', delay = '0', origin = '' } = option
      const at = setTimeout(() => {
        item.style = { ...item.style, transition: `all ${duration}s ${tf} ${delay}s`, transform: '' }
        if (origin !== undefined) item.style.transformOrigin = origin
        if (type === 'out') {
          transName.forEach(n => {
            if (option[n] !== undefined) item.style.transform += ` ${n}(${option[n]})`
          })
        }
        clearTimeout(at)
      }, 30)
      if (type === 'in' || callback) {
        const t = setTimeout(() => {
          if (callback) callback()
          else {
            delete item.style.transition
            delete item.style.transformOrigin
          }
          clearTimeout(t)
        }, (Number(duration) + Number(delay)) * 1000 + 40)
      }
    }
  },
})
